//
//  LRComposeVC.swift
//  WeiboX
//
//  Created by admin on 10/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit
import SVProgressHUD

class LRComposeVC: UIViewController {
	
	var callBack: (() -> ())?
	
	// 自定义表情键盘
	fileprivate lazy var emotionKb: LREmoticonKeyboard = {
		let keyboard = LREmoticonKeyboard()
		keyboard.size = CGSize(width: ScreenWidth, height: 216)
		return keyboard
	}()
	
	// po 按钮
	lazy var postBtn: UIButton = {
		let btn = UIButton()
		
		btn.addTarget(self, action: #selector(postBtnAction), for: .touchUpInside)
		
		btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
		btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
		btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
		
		btn.setTitle("post", for: .normal)
		btn.titleLabel?.font = .systemFont(ofSize: 15)
		
		btn.setTitleColor(.white, for: .normal)
		btn.setTitleColor(.gray, for: .disabled)
		
		btn.size = CGSize(width: 45, height: 35)
		
		return btn
	}()
	
	// 标题富文本
	lazy var navTitle: UILabel = {
		let label = UILabel(fontSize: 17, textColor: .darkGray)
		if let name = LRUserAccountVM.sharedUserAccount.userAccount?.name {
			let result = "发微博\n\(name)"
			// 富文本
			let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: result)
			// name range
			let range = (result as NSString).range(of: name)
			
			attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.brown], range: range)
			
			label.attributedText = attributedStr
		} else {
			label.text = "发微博"
		}
		
		label.numberOfLines = 0
		label.textAlignment = .center
		label.sizeToFit()
		
		return label
	}()
	
	// 底部 toolBar
	fileprivate lazy var toolBar: LRComposeToolBar = {
		let toolBar = LRComposeToolBar()
		return toolBar
	}()
	
	// 自定义 textView
	fileprivate lazy var textView: LRComposeTextView = {
		let textView = LRComposeTextView()
		textView.placeHolder = "测试文本 test text 测试文本 test text 测试文本 test text 测试文本 test text 测试文本 test text 测试文本 test text 测试文本 test text 测试文本 test text 测试文本 test text"
//		textView.backgroundColor = .red
		textView.delegate = self
		textView.font = .systemFont(ofSize: 14)
		textView.alwaysBounceVertical = true
		textView.backgroundColor = .yellow
		
		return textView
	}()
	
	// 自定义 picCollectionView
	fileprivate lazy var picCollectionView: LRComposePicCollectionV = {
		let collectionView = LRComposePicCollectionV()

		collectionView.backgroundColor = .green
		return collectionView
	}()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
	
	private func setupUI() {
		view.backgroundColor = .white
		
		// 监听键盘 frame 变化
		NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChanged(noti:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
		
		// 监听表情键盘表情的点击
		NotificationCenter.default.addObserver(self, selector: #selector(didSelectedEmoticonBtn(noti:)), name: Notification.Name(DidSelectedEmoticonBtnName), object: nil)
		
		setupNavUI()
		
		view.addSubview(textView)
		view.addSubview(toolBar)
		textView.addSubview(picCollectionView)
		
		toolBar.snp.makeConstraints { (make) in
			make.leading.bottom.trailing.equalToSuperview()
			make.height.equalTo(35)
		}
		
		textView.snp.makeConstraints { (make) in
			make.leading.top.trailing.equalToSuperview()
			make.bottom.equalTo(toolBar.snp.top)
		}
		
		picCollectionView.snp.makeConstraints { (make) in
			make.top.equalToSuperview().offset(100)
			make.centerX.equalToSuperview()
			make.size.equalTo(CGSize(width: view.width - 20, height: view.width - 20))
		}
		
		toolBar.callBack = { [weak self] (type) -> Void in
			switch type {
			case .camera:
				print("点击相机")
				self?.appendPic()
			case .mention:
				print("@")
			case .trend:
				print("#")
			case .emoticon:
				print("点击表情")
				self?.didSelectedEmoticon()
			case .add:
				print("点击加号")
			}
		}
		
		picCollectionView.callBack = { [weak self] in
			self?.appendPic()
		}
	}
	
	private func setupNavUI() {
		navigationItem.titleView = navTitle
		navigationItem.leftBarButtonItem = UIBarButtonItem(title: "cancel", target: self, action: #selector(cancelBtnAction))
		navigationItem.rightBarButtonItem = UIBarButtonItem(customView: postBtn)
		navigationItem.rightBarButtonItem?.isEnabled = false
	}
	
	@objc private func didSelectedEmoticonBtn(noti: Notification) {
		let emoticon = noti.object as! LREmoticon
		if emoticon.type == "0" {
			print(emoticon.chs!)
			textView.insertText(emoticon.chs!)
		} else {
			print((emoticon.code! as NSString).emoji())
			textView.insertText((emoticon.code! as NSString).emoji())
		}
	}
	
	@objc private func keyboardFrameChanged(noti: Notification) {
		let keyboardFrame = (noti.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
		let duration = (noti.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
		
		// 更新约束
		toolBar.snp.updateConstraints { (make) in
			make.bottom.equalToSuperview().offset(-ScreenHeight + keyboardFrame.origin.y)
		}
		
		UIView.animate(withDuration: duration) {
			self.view.layoutIfNeeded()
		}
	}
	
	@objc private func cancelBtnAction() {
		self.dismiss(animated: true, completion: nil)
	}
	
	@objc private func postBtnAction() {
		let status = textView.text!
		
		SVProgressHUD.show()
		
		if picCollectionView.dataArr.count > 0 {
			LRNetworkManager.sharedManager.postNewPicStatus(status: status, pic: picCollectionView.dataArr.first!, callBack: { (responseObj, error) in
				if error != nil {
					print("发送失败")
					SVProgressHUD.showError(withStatus: "faild to send")
					return
				}
				SVProgressHUD.showSuccess(withStatus: "success")
				print("发送成功")
			})
		} else {
			LRNetworkManager.sharedManager.postNewStatus(status: status) { (responseObj, error) in
				if error != nil {
					print("发送失败")
					SVProgressHUD.showError(withStatus: "faild to send")

					return
				}
				SVProgressHUD.showSuccess(withStatus: "success")

				print("发送成功")
			}
		}
	}
	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}
	
	deinit {
		NotificationCenter.default.removeObserver(self)
	}
}

extension LRComposeVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
	// 切换表情键盘的方法
	func didSelectedEmoticon() {
		if textView.inputView == nil {
			textView.inputView = emotionKb
			toolBar.switchEmoticonIcon(isEmoticon: true)
		} else {
			textView.inputView = nil
			toolBar.switchEmoticonIcon(isEmoticon: false)
		}
		
		textView.becomeFirstResponder()	// 设置为第一视图
		textView.reloadInputViews()	// 重载自定义的 inputView
	}
	
	// 新增图片的方法
	fileprivate func appendPic() {
		let pickerCtrler = UIImagePickerController()
		
		pickerCtrler.delegate = self
		
		// 判断来源
		if UIImagePickerController.isSourceTypeAvailable(.camera) {
			pickerCtrler.sourceType = .camera
		} else {
			pickerCtrler.sourceType = .photoLibrary
		}
		
		//		pickerCtrler.allowsEditing = true	// 可以编辑
		
		// 判断前后摄像头是否可用
		if UIImagePickerController.isCameraDeviceAvailable(.front) {
			// 前置可用
		}
		if UIImagePickerController.isCameraDeviceAvailable(.rear) {
			// 后置可用
		}
		
		self.present(pickerCtrler, animated: true, completion: nil)
	}
	
	// MARK: - UIImagePickerControllerDelegate
	internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
		let img = info[UIImagePickerControllerOriginalImage] as! UIImage
		// 获取压缩后的图片
		let scaleImg = self.scaleImg(scaleWidth: 200, img: img)
		
		picCollectionView.addImage(img: scaleImg)
		
		picker.dismiss(animated: true, completion: nil)
	}
	
	internal func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
		picker.dismiss(animated: true, completion: nil)
	}
	
	// 压缩图片
	private func scaleImg(scaleWidth: CGFloat, img: UIImage) -> UIImage {
		let scaleHeight: CGFloat = scaleWidth * img.size.height / img.size.width
		let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
		
		
		UIGraphicsBeginImageContext(scaleSize)
		
		img.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
		
		let currentImg = UIGraphicsGetImageFromCurrentImageContext()
		
		UIGraphicsEndImageContext()
		
		return currentImg!
	}
}

extension LRComposeVC: UITextViewDelegate {
	func textViewDidChange(_ textView: UITextView) {
		navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
	}
	
	func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
		self.view.endEditing(true)
	}
}
